package com.jy.horny.utils

import android.content.Context
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.util.SparseIntArray
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.widget.ImageView
import androidx.annotation.DrawableRes
import androidx.core.app.ActivityCompat
import com.bumptech.glide.Glide
import com.bumptech.glide.load.Transformation
import com.bumptech.glide.request.RequestOptions
import com.jy.horny.App
import com.jy.horny.base.workScheduler
import com.jy.horny.utils.Injections.mainHandler
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import jp.wasabeef.glide.transformations.RoundedCornersTransformation

object ImageCached {
    // 使用了缓存优化的url容器
    private val thumbnails = mutableMapOf<String, String>()

    // 使用了缓存优化的尺寸容器
    private val dps = SparseIntArray()

    // 使用了缓存优化的颜色容器
    private val colors = mutableMapOf<String, Int>()

    fun dp2px(dpValue: Int): Int {
        return dp2px(dpValue, appContext)
    }

    fun dp2px(dpValue: Int, context: Context): Int { // if use viewContext can load preview
        val result = dps[dpValue]
        if (result > 0) return result
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dpValue.toFloat(),
            context.resources.displayMetrics
        ).toInt().also {
            dps.put(dpValue, it)
        }
    }

    fun getColor(color: String): Int {
        val result = colors[color]
        if (result != null) return result
        return try {
            Color.parseColor(color).also { colors[color] = it }
        } catch (e: Exception) {
            e.printStackTrace()
            Color.TRANSPARENT
        }
    }

    // 是否进行url优化
    private fun opt(url: String?): Boolean {
        if (url.isNullOrEmpty()) return false
        if (url.contains("google")) return false
        if (url.contains("facebook")) return false
        return true
    }

    fun thumbnail(
        url: String?,
        width: Int,
        height: Int = width,
        quality: Int = 75,
        type: Int = 8
    ): String? {
        if (!opt(url)) return url // maybe user avatar url startWith http://graph.facebook.com/
        val cacheKey = "$url-$width-$height-$quality"
        val result = thumbnails[cacheKey]
        if (!result.isNullOrEmpty()) return result
        // https://docs.ucloud.cn/storage_cdn/ufile/service/pic
        val processedUrl = if (width == 0 && height == 0) {
            "$url?iopcmd=convert&dst=webp&Q=$quality"
        } else {
            "$url?iopcmd=convert&dst=${getDst(url)}&Q=$quality|iopcmd=thumbnail&type=$type&width=$width&height=$height"
        }
        return processedUrl.also {
            thumbnails[cacheKey] = it
        }
    }

    private fun getDst(url: String?): String {
        if (url == null)
            return "jpeg"
        val suffix = url.substring(url.lastIndexOf(".") + 1)
        if (suffix == "jpeg") return "jpeg"
        else if (suffix == "jpg") return "jpg"
        else if (suffix == "png") return "png"

        return "webp" // dst=com/123-1617182047199. 隐藏格式的url
    }

}
/**
 * @Author andy
 * @Date 2024/5/28 14:44
 */
/** 获得全局appContext */
val appContext: Context get() = App.context!!
fun dpToPx(dpValue: Int) = ImageCached.dp2px(dpValue) // 全局px转化dp

// 屏幕宽度
fun screenWidth() = appContext.resources.displayMetrics.widthPixels

object Injections {
    /** Glide 加载图片的Transform变化.输出圆角图片 */
    val transformRounded5 by lazy { RoundedCornersTransformation(dpToPx(5), 0) }
    val transformRounded10 by lazy { RoundedCornersTransformation(dpToPx(10), 0) }
    val transformRounded14 by lazy { RoundedCornersTransformation(dpToPx(14), 0) }

    /** Glide 加载图片的Transform变化.输出圆角图片 */
    val transformRounded20Top by lazy {
        RoundedCornersTransformation(
            dpToPx(20),
            0,
            RoundedCornersTransformation.CornerType.TOP
        )
    }

    /** Glide 加载图片的Transform变化.输出圆形图片 */
    val transformCropCircle by lazy { com.bumptech.glide.load.resource.bitmap.CircleCrop() }

    val mainHandler by lazy { Handler(Looper.getMainLooper()) }

    /** view动画.收缩弹一下 */
    val animScaleKick by lazy {
        AnimationUtils.loadAnimation(
            appContext,
            com.lib.module_res.R.anim.anims_scale_kick
        )!!
    }


    val screenWidthD2 by lazy { screenWidth() / 2 }
}

fun ViewGroup.inflate(resId: Int): View {
    return LayoutInflater.from(context).inflate(resId, this, false)
}

fun isMainThread() = Looper.myLooper() == Looper.getMainLooper()

/** 此线程【work线程】仅专做计算calc. 数据变化使用此方法，其他功能逻辑不要调用。 */
fun runOnWorkThread(block: () -> Unit): Disposable = Observable.fromCallable { block() }
    .subscribeOn(workScheduler).subscribe()

// 此线程【ui线程】专做ui渲染
fun runOnUIThread(block: () -> Unit) {
    if (isMainThread()) {
        block()
    } else {
        mainHandler.post(block)
    }
}

/**
 * ImageView 使用Glide加载缩略图. 缩略图服务为OSS服务供应商提供的服务.
 * 实现方式是在url上进行参数的拼接文档见 https://docs.ucloud.cn/storage_cdn/ufile/service/pic
 * url            图片http地址
 * width          裁剪宽
 * height         裁剪高
 * quality        图片质量
 * type           裁剪模式
 * placeHolder    静态占位图
 * transformation 对图片的显示进行圆形. 圆角处理
 */
fun ImageView.loadThumbnails(
    url: String?,
    width: Int,
    height: Int = width,
    quality: Int = 75,
    type: Int = 8,
    placeHolder: Int? = null,
    errorHolder: Int? = null,
    transformation: Transformation<Bitmap>? = null
) {
    val thumbnailsUrl =
        if (url.isNullOrEmpty()) "" else ImageCached.thumbnail(url, width, height, quality, type)
    load(thumbnailsUrl, placeHolder, errorHolder, transformation)
}

/**
 * ImageView 使用Glide直接加载url地址. 一般情况下最好调用 loadThumbnails 加载缩略图
 */
fun ImageView.load(
    url: String?, placeHolder: Int? = null, errorHolder: Int? = null,
    transformation: Transformation<Bitmap>? = null
) {
    //log("image load $url")
    if (url.isNullOrEmpty()) {
        setImageResource(placeHolder ?: com.lib.module_res.R.color.transparent)
        return
    }
    Glide.with(this).load(url)
        .apply {
            if (placeHolder != null || errorHolder != null || transformation != null) {
                apply(RequestOptions().apply {
                    if (placeHolder != null) placeholder(placeHolder)
                    if (errorHolder != null) error(errorHolder)
                    if (transformation != null) transform(transformation)
                })
            }
        }
        .into(this)
}

/**
 * ImageView 使用Glide加载本地资源
 */
fun ImageView.load(
    @DrawableRes resId: Int, placeHolder: Int? = null, errorHolder: Int? = null,
    transformation: Transformation<Bitmap>? = null
) {
    Glide.with(this).load(resId)
        .apply {
            if (placeHolder != null || errorHolder != null || transformation != null) {
                apply(RequestOptions().apply {
                    if (placeHolder != null) placeholder(placeHolder)
                    if (errorHolder != null) error(errorHolder)
                    if (transformation != null) transform(transformation)
                })
            }
        }
        .into(this)
}